<template>
    <div>
        <el-container>
            <el-header>
                <el-row style="padding: 10px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                    <el-col :span="4">
                        <span style="font-size: 20px; font-weight: 1000; color: white">
                            <el-icon><HomeFilled /></el-icon>{{ $t('操作日志') }}
                        </span>
                    </el-col>
                    <el-col :span="20">
                        <div style="float: right">
                            <UiSet :type="2" :index="0" :Prop="uiSectionList" :comid="componentId" v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                        </div>
                    </el-col>
                </el-row>
            </el-header>
            <el-main style="padding: 0%">
                <div>
                    <el-card style="height: auto">
                        <el-form :model="findform" :inline="true" label-width="120px">
                            <el-row :gutter="10">
                                <template v-for="(item, index) in Stores.comui[componentId][0].baseProps">
                                    <el-col v-if="item.visible && item.ismore == false" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                        <el-form-item :label="I(item.label, item.labeleng)">
                                            <template #default>
                                                <div v-if="item.type === 'date'">
                                                    <el-date-picker v-model="findform[item.prop]" type="daterange" :start-placeholder="$t('开始')" :end-placeholder="$t('结束')" style="width: 200px" />
                                                </div>
                                                <div v-else-if="item.prop === 'state'">
                                                    <el-select v-model="findform[item.prop]" :id="item.prop" size="default" style="width: 160px" placeholder="">
                                                        <el-option :label="$t('全部')" value="null" />
                                                        <el-option :label="$t('在线')" value="1" />
                                                        <el-option :label="$t('离线')" value="0" />
                                                    </el-select>
                                                </div>
                                                <div v-else-if="item.type === 'number'">
                                                    <el-input-number style="width: 160px" v-model="findform[item.prop]" :controls="false" :id="item.prop"></el-input-number>
                                                </div>
                                                <div v-else>
                                                    <el-input clearable v-model="findform[item.prop]" :id="item.prop" />
                                                </div>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                </template>
                                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                                    <el-form-item>
                                        <el-button color="#e1d8d8" round :icon="Refresh" @click="resetForm()" id="reset">{{ $t('重置') }}</el-button>
                                        <el-button v-loading="loading" type="primary" round :icon="Search" @click="gettablelist()" id="find">{{ $t('查找') }}</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-card>
                    <el-row style="padding: 5px; background: linear-gradient(89deg, rgb(56 162 249), rgb(155 255 255))" justify="space-between">
                        <el-col :span="4">
                            <span style="font-size: 20px; font-weight: 1000; color: white">
                                <el-icon><Grid /></el-icon>{{ $t('列表数据') }}
                            </span>
                        </el-col>
                        <el-col :span="20">
                            <el-row justify="end" :gutter="10">
                                <el-button v-loading="loading" color="#00b794" :icon="Document" round @click="exportEvent" style="margin-left: 10px">{{ $t('Excel导出') }} </el-button>
                                <UiSet :type="1" :index="0" :Prop="uiSectionList" :comid="componentId" v-model:isgrant="isuigrant" @before-click="uisetbefore"></UiSet>
                            </el-row>
                        </el-col>
                    </el-row>
                    <el-card>
                        <div v-loading="loading">
                            <vxe-table :data="tablelist" border show-overflow height="400" :mouse-config="{ selected: true }" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }">
                                <vxe-column v-for="(column, index) in Stores.comui[componentId][0].tableProps" :field="column.prop" :title="column.label" :width="column.width" :fixed="column.fixed" :align="column.align">
                                    <template #header>
                                        <div v-if="column.type === 'checkbox'">
                                            <el-checkbox v-model="Allcheck" @change="CheckAllChange" />
                                        </div>
                                        <div v-else>
                                            {{ I(column.label, column.labeleng) }}
                                        </div>
                                    </template>
                                    <template #default="{ row, rowIndex }">
                                        <div v-if="column.type === 'checkbox'">
                                            <el-checkbox v-model="row['checked']" />
                                        </div>
                                        <div v-else>
                                            {{ row[column.prop] }}
                                        </div>
                                    </template>
                                </vxe-column>
                            </vxe-table>
                        </div>
                        <pagemodel v-model:allcount="allcount" v-model:page="findform.page" v-model:pagecount="findform.pagecount" @pagechange="pagechange"></pagemodel>
                    </el-card>
                </div>
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import { httpSend } from '@/utils/api';
import { getCurrentInstance, onMounted, ref, reactive, watch, toRaw } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { Refresh, Search, Plus, Document, Delete } from '@element-plus/icons-vue';
/*组件*/
import UiSet from '@/components/share/UiSet.vue';
import excel from '@/components/share/excel.vue';
import pagemodel from '@/components/share/pagemodel.vue';
//@ts-ignore
import { TableUiSection } from '@/components/share/ui-set.interface.ts';
import * as XLSX from 'xlsx'; /*excel操作*/
//@ts-ignore
import { useshareStore } from '@/store'; /*pina管理*/
import { formatDate, chkgrant } from '@/globalmethods'; /*通用方法*/
const excelRef = ref(null);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
const { t } = useI18n(); //多语言
// 自定义字段配置
const componentId = 'operatorlogsetting';
let uiSectionList: TableUiSection[] = [
    {
        baseProps: [
            { label: '操作人', prop: 'operator', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '单据类型', prop: 'billcaption', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '操作类型', prop: 'type', visible: true, readonly: false, type: 'string', ismore: false },
            { label: '操作时间', prop: 'editdate', visible: true, readonly: false, type: 'date', ismore: false },
        ],
        tableProps: [
            { label: '操作人', labelex: '', labeleng: '', prop: 'operator', visible: true, readonly: false, width: '100', type: 'string', fixed: null, align: 'left' },
            { label: '单据类型', labelex: '', labeleng: '', prop: 'billcaption', visible: true, readonly: false, width: '150', type: 'string', fixed: null, align: 'center' },
            { label: '操作时间', labelex: '', labeleng: '', prop: 'editdate', visible: true, readonly: false, width: '180', type: 'string', fixed: null, align: 'center' },
            { label: '操作类型', labelex: '', labeleng: '', prop: 'type', visible: true, readonly: false, width: '150', type: 'string', fixed: null, align: 'center' },
            { label: '操作内容', labelex: '', labeleng: '', prop: 'des', visible: true, readonly: false, width: '500', type: 'string', fixed: null, align: 'center' },
        ],
    },
];
const loading = ref(false);
const findform = reactive({
    Loginuserid: null,
    Loginuser: null,
    logintime: null,
    state: null,
    page: 1,
    pagecount: 50,
});
const Allcheck = ref(false);
const allcount = ref(0); // 总数据条数
const tablelist = ref([]); // 表格数据
const isuigrant = ref(false);
const Stores = useshareStore() as any;
Stores.setcomui([componentId, uiSectionList]);
onMounted(() => {
    //加载权限
    isuigrant.value = chkgrant('操作日志', 'customset');
    getuiset();
    gettablelist();
});

//获取配置数据
const getuiset = async () => {
    loading.value = true;
    let comdata = [];
    comdata[0] = componentId;
    comdata[1] = [];
    Object.assign(comdata[1], uiSectionList);
    const fd = new FormData();
    let data = { comid: componentId, userid: null };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getComUiSet', fd, false);
    if (res && res.code == 1) {
        if (res.data.length > 0) {
            let data = JSON.parse(res.data[0]['setjson']);
            // 如果数据依然是字符串，则需要再解析一次
            if (typeof data === 'string') {
                data = JSON.parse(data); // 第二次解析
            }
            if (data) {
                Object.assign(comdata[1], data);
            }
        }
    }
    loading.value = false;
    Stores.setcomui(comdata);
};

const gettablelist = async () => {
    if (!chkgrant('操作日志', 'getoperatelog')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    //Object.entries(findform).filter(([key, value]) => value !== null)
    loading.value = true;
    tablelist.value = [];
    let data = JSON.parse(JSON.stringify(toRaw(findform)));
    if (data.editdate) {
        data['datebegin'] = formatDate(findform.editdate[0], 'yyyy-MM-dd');
        data['dateend'] = formatDate(findform.editdate[1], 'yyyy-MM-dd');
        delete data.editdate;
    }
    const fd = new FormData();
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('getoperatelog', fd, false);
    if (res && res.data && res.code == 1) {
        tablelist.value = res.data.map((v) => {
            return {
                ...v,
                timeoutcount: Number(v.timeoutcount) / 60,
            };
        });
        allcount.value = res.count;
    }
    loading.value = false;
};

//表头全选/取消
const CheckAllChange = (val: boolean) => {
    tablelist.value.forEach((v) => {
        v.checked = val;
    });
    tablelist.value = [...tablelist.value];
};
//重置
const resetForm = () => {
    for (let key in findform) {
        if (findform.hasOwnProperty(key)) {
            findform[key] = null;
        }
    }
};
//页数变化重新查询
const pagechange=(e)=>{
    gettablelist();
}
//导出
const exportEvent = () => {
    if (!chkgrant('操作日志', 'excelout')) {
        ElMessage.warning(t('您暂无导出权限,请联系管理员!'));
        return;
    }
    const formattedData = tablelist.value.map((row) => {
        // 创建一个新的对象
        const newRow = {};
        Stores.comui[componentId][0].tableProps.forEach((v) => {
            if (v.visible && v.prop != 'action' && v.prop != 'checked') {
                newRow[v.label] = !!row[v.prop] ? row[v.prop] : '';
            }
        });
        return newRow; // 返回新创建的对象
    });
    // 使用自定义标题和数据生成工作表
    const ws = XLSX.utils.json_to_sheet(formattedData); // { header }
    // 创建一个新的工作簿
    const wb = XLSX.utils.book_new();
    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    // 使用文件名导出 Excel 文件
    XLSX.writeFile(wb, t('操作日志导出') + '.xlsx');
};
//自定义配置权限判断
const uisetbefore = () => {
    if (!isuigrant.value) {
        ElMessage.warning(t('您暂无配置权限,请联系管理员!'));
        return;
    }
};
const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>
<style scoped>
:deep(.el-header) {
    --el-header-padding: 0 20px;
    --el-header-height: 60px;
    box-sizing: border-box;
    flex-shrink: 0;
    height: auto;
    padding: 0;
}
:deep(.el-card__body) {
    padding: 5px !important;
    color: #000000;
}
</style>
